package com.example.musicplayer.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;

import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.musicplayer.R;
import com.example.musicplayer.commonUtils.ToastUtil;
import com.example.musicplayer.dialogTools.ImageDisplayDialog;
import com.example.musicplayer.musicClass.MusicInfo;
import com.example.musicplayer.musicClass.MusicMenu;
import com.example.musicplayer.settings.MusicPlayerSettings;
import com.example.musicplayer.user.User;
import com.example.musicplayer.view.MusicMenuCoverDisplay;
import com.example.musicplayer.windowTools.WindowTools;

import java.util.ArrayList;
import java.util.List;

public class SelectMusicMenuCoverActivity extends BaseActivity {
    public static final int RESULT_CODE = 500;
    public static final String SELECT_MODE = "selectMode";
    public static final int MODE_MENU_COVER = 1;
    public static final int MODE_USER_PHOTO = 2;
    public static final int MODE_PLAY_SCREEN = 3;
    public static final int MODE_MUSIC_PLAY_LIST = 4;
    //加载图片的时间间隔
    private static final int LOAD_BITMAP_TIME_GAP = 10;
    private TextView mConfirm;
    private LinearLayout mContainerLeft;
    private LinearLayout mContainerRight;
    private int mMode;
    private boolean mStateChanged = false;
    //是否有图片被选中
    private boolean mIsCoverSelected = false;
    //当前加载的图片的索引
    private int mCurrentLoadIndex = 0;
    //当前封面图的索引
    private int mStartSelected;
    private MusicMenu mMusicMenu;
    private final List<MusicInfo> mMusicInfo = new ArrayList<MusicInfo>();
    private final List<MusicMenuCoverDisplay> mDisplay = new ArrayList<MusicMenuCoverDisplay>();
    private final Object mDisplayObject = new Object();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_music_menu_cover);
        WindowTools.lightStatusBar(getWindow());

        Intent intent = getIntent();
        mMode = intent.getIntExtra(SELECT_MODE, MODE_MENU_COVER);
        String menuName = intent.getStringExtra("musicMenuName");
        mMusicMenu = MusicInfo.getMusicMenuByName(menuName);
        initView();
        addListener();
        updateList();
        setEnableTimer(true, false);
        setTimerInterval(LOAD_BITMAP_TIME_GAP);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && mCurrentLoadIndex < mMusicInfo.size()) {
            startTimer();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        pauseTimer();
    }

    @Override
    public void onBackPressed() {
        finishActivity();
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finishActivity();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected boolean onRefreshView() {
        if (mCurrentLoadIndex < mMusicInfo.size()) {
            MusicMenuCoverDisplay display = new MusicMenuCoverDisplay();
            display.update(mMusicInfo.get(mCurrentLoadIndex));
            addListener(display);
            synchronized (mDisplayObject) {
                mDisplay.add(display);
            }
            if (mCurrentLoadIndex % 2 == 0)
                mContainerLeft.addView(display.getView());
            else
                mContainerRight.addView(display.getView());
            if (mCurrentLoadIndex == mStartSelected && !mIsCoverSelected) {
                display.setSelected(true);
            }
            mCurrentLoadIndex++;
            return true;
        } else {
            return false;
        }
    }

    private void initView() {
        Toolbar toolbar = findViewById(R.id.toolbar_select_music_menu_cover);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            //添加向上操作
            actionBar.setDisplayHomeAsUpEnabled(true);
            //去除toolbar中的标题
            actionBar.setDisplayShowTitleEnabled(false);
        }

        mConfirm = findViewById(R.id.textview_select_music_menu_cover_confirm);
        mContainerLeft = findViewById(R.id.linear_layout_container_left);
        mContainerRight = findViewById(R.id.linear_layout_container_right);
    }

    private void addListener() {
        mConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doClickSave();
            }
        });
    }

    private void addListener(final MusicMenuCoverDisplay display) {
        display.getImageViewCover().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doClickItem(display);
            }
        });
        display.getImageViewCover().setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                int musicId;
                if (display.getMusicInfo() == null) {
                    musicId = 0;
                } else {
                    musicId = display.getMusicInfo().getId();
                }
                showImageDisplayDialog(musicId);
                return true;
            }
        });
    }

    //初始化显示的图片列表
    private void updateList() {
        mMusicInfo.clear();
        mMusicInfo.add(null);
        if (mMode == MODE_MENU_COVER && mMusicMenu != null) {
            for (int i = 0; i < mMusicMenu.getCounts(); i++) {
                MusicInfo temp = mMusicMenu.getMusicInfo(i);
                boolean hasThisAlbum = false;
                for (int j = 1; j < mMusicInfo.size(); j++) {
                    if (temp.getAlbum().equals(mMusicInfo.get(j).getAlbum())) {
                        hasThisAlbum = true;
                        break;
                    }
                }
                if (!hasThisAlbum) {
                    mMusicInfo.add(temp);
                }
            }
            //计算初始选中的索引号
            mStartSelected = 0;
            if (mMusicMenu != null) {
                MusicInfo currentInfo = MusicInfo.getMusicInfoById(mMusicMenu.getBitmapId());
                if (currentInfo != null) {
                    for (int i = 1; i < mMusicInfo.size(); i++)
                        if (currentInfo.getAlbum().equals(mMusicInfo.get(i).getAlbum())) {
                            mStartSelected = i;
                            break;
                        }
                }
            }
        } else if (mMode == MODE_USER_PHOTO || mMode == MODE_PLAY_SCREEN || mMode == MODE_MUSIC_PLAY_LIST) {
            List<MusicInfo> list = MusicInfo.getLocalMusic();
            for (int i = 0; i < list.size(); i++) {
                MusicInfo temp = list.get(i);
                boolean hasThisAlbum = false;
                for (int j = 1; j < mMusicInfo.size(); j++) {
                    if (temp.getAlbum().equals(mMusicInfo.get(j).getAlbum())) {
                        hasThisAlbum = true;
                        break;
                    }
                }
                if (!hasThisAlbum) {
                    mMusicInfo.add(temp);
                }
            }
            //计算初始选中的索引号
            mStartSelected = 0;
            int currentId = 0;
            if (mMode == MODE_USER_PHOTO) {
                User user = User.getInstance();
                if (user != null) {
                    currentId = user.getUserPhotoId();
                }
            } else if (mMode == MODE_PLAY_SCREEN) {
                currentId = MusicPlayerSettings.getPlayScreenImageId();
            } else {
                currentId = MusicPlayerSettings.getMusicPlayListImageId();
            }
            MusicInfo currentInfo = MusicInfo.getMusicInfoById(currentId);
            if (currentInfo != null) {
                for (int i = 1; i < mMusicInfo.size(); i++) {
                    if (currentInfo.getAlbum().equals(mMusicInfo.get(i).getAlbum())) {
                        mStartSelected = i;
                        break;
                    }
                }
            }
        }
    }

    private void showImageDisplayDialog(int musicId) {
        List<Integer> idList = new ArrayList<Integer>();
        int displayPosition = 0;
        //null bitmap
        idList.add(0);
        for (int i = 1; i < mMusicInfo.size(); i++) {
            int id = mMusicInfo.get(i).getId();
            idList.add(id);
            if (id == musicId) {
                displayPosition = i;
            }
        }
        final ImageDisplayDialog dialog = new ImageDisplayDialog(this);
        dialog.setImage(idList, displayPosition);
        dialog.setConfirmListener(new ImageDisplayDialog.ConfirmListener() {
            @Override
            public void onConfirm(int position) {
                doClickItem(mDisplay.get(position));
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    //获取选中的序号
    private int getSelectedNumber() {
        synchronized (mDisplayObject) {
            for (int i = 0; i < mDisplay.size(); i++)
                if (mDisplay.get(i).getSelected())
                    return i;
            mDisplay.get(0).setSelected(true);
            return 0;
        }
    }

    private void doClickItem(MusicMenuCoverDisplay display) {
        if (!display.getSelected()) {
            mDisplay.get(getSelectedNumber()).setSelected(false);
            display.setSelected(true);
            mIsCoverSelected = true;
        }
    }

    //点击保存
    private void doClickSave() {
        if (!mIsCoverSelected) {
            mStateChanged = false;
        } else {
            int nowSelected = getSelectedNumber();
            int bitmapId = nowSelected == 0 ? 0 : mDisplay.get(nowSelected).getMusicInfo().getId();
            if (nowSelected != mStartSelected) {
                if (mMode == MODE_MENU_COVER && mMusicMenu != null) {
                    ToastUtil.makeToast(getString(R.string.success_to_change_menu_cover));
                    mStateChanged = true;
                    mMusicMenu.setBitmap(bitmapId);
                } else if (mMode == MODE_USER_PHOTO) {
                    if (User.getInstance() != null && User.getInstance().setUserPhoto(bitmapId)) {
                        ToastUtil.makeToast(getString(R.string.success_to_change_user_photo));
                        mStateChanged = true;
                    }
                } else if (mMode == MODE_PLAY_SCREEN) {
                    MusicPlayerSettings.setPlayScreenImage(bitmapId);
                    ToastUtil.makeToast(getString(R.string.success_change_play_screen_background));
                    mStateChanged = true;
                } else if (mMode == MODE_MUSIC_PLAY_LIST) {
                    MusicPlayerSettings.setMusicPlayListImage(bitmapId);
                    ToastUtil.makeToast(getString(R.string.success_change_music_play_list_background));
                    mStateChanged = true;
                }
            }
        }
        finishActivity();
    }

    //返回
    private void finishActivity() {
        Intent intent = new Intent();
        intent.putExtra("result", mStateChanged);
        intent.putExtra(SELECT_MODE, mMode);
        this.setResult(RESULT_CODE, intent);
        finish();
        setPendingTransition(R.anim.fake_anim, R.anim.activity_vertical_exit);
    }
}